using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.Dtos;
using UniversalAdmin.Application.Dtos.Article;
using UniversalAdmin.Application.Services.Interfaces;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ArticleController : ControllerBase
{
    private readonly IArticleService _articleService;

    public ArticleController(IArticleService articleService)
    {
        _articleService = articleService;
    }

    /// <summary>
    /// 获取所有文章列表（分页查询）
    /// </summary>
    /// <param name="pageRequestDto">分页查询参数</param>
    /// <returns>分页文章列表</returns>
    [HttpGet]
    public async Task<IActionResult> GetAllArticles([FromQuery] PageRequestDto pageRequestDto)
    {
        var articles = await _articleService.GetPagedAsync(pageRequestDto);
        return Ok(articles);
    }

    /// <summary>
    /// 根据ID获取文章详情
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <returns>文章详情</returns>
    [HttpGet("{articleId}")]
    public async Task<IActionResult> GetArticleById(Guid articleId)
    {
        var article = await _articleService.GetByIdAsync(articleId);
        if (article == null)
            return NotFound("未找到文章");
        return Ok(article);
    }

    /// <summary>
    /// 根据分类ID获取文章列表
    /// </summary>
    /// <param name="categoryId">分类ID</param>
    /// <returns>文章列表</returns>
    [HttpGet("category/{categoryId}")]
    public async Task<IActionResult> GetArticlesByCategory(Guid categoryId)
    {
        var articles = await _articleService.GetByCategoryIdAsync(categoryId);
        return Ok(articles);
    }

    /// <summary>
    /// 根据状态获取文章列表
    /// </summary>
    /// <param name="status">文章状态</param>
    /// <returns>文章列表</returns>
    [HttpGet("status/{status}")]
    public async Task<IActionResult> GetArticlesByStatus(string status)
    {
        var articles = await _articleService.GetByStatusAsync(status);
        return Ok(articles);
    }

    /// <summary>
    /// 搜索文章
    /// </summary>
    /// <param name="keyword">搜索关键词</param>
    /// <returns>搜索结果</returns>
    [HttpGet("search")]
    public async Task<IActionResult> SearchArticles([FromQuery] string keyword)
    {
        if (string.IsNullOrWhiteSpace(keyword))
            return BadRequest("搜索关键词不能为空");

        var articles = await _articleService.SearchAsync(keyword);
        return Ok(articles);
    }

    /// <summary>
    /// 创建新文章
    /// </summary>
    /// <param name="createArticleDto">文章创建参数</param>
    /// <returns>创建结果</returns>
    [HttpPost]
    public async Task<IActionResult> CreateArticle([FromBody] CreateArticleDto createArticleDto)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        try
        {
            var article = await _articleService.CreateAsync(createArticleDto);
            return CreatedAtAction(nameof(GetArticleById), new { articleId = article.Id }, article);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 更新文章信息
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <param name="updateArticleDto">文章更新参数</param>
    /// <returns>更新结果</returns>
    [HttpPut("{articleId}")]
    public async Task<IActionResult> UpdateArticle(Guid articleId, [FromBody] UpdateArticleDto updateArticleDto)
    {
        if (articleId != updateArticleDto.Id)
            return BadRequest("ID 不匹配");

        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        try
        {
            var article = await _articleService.UpdateAsync(updateArticleDto);
            return Ok(article);
        }
        catch (ArgumentException ex)
        {
            return NotFound(ex.Message);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 删除文章（软删除）
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("{articleId}")]
    public async Task<IActionResult> DeleteArticle(Guid articleId)
    {
        try
        {
            await _articleService.DeleteAsync(articleId);
            return Ok("文章删除成功");
        }
        catch (ArgumentException ex)
        {
            return NotFound(ex.Message);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

    /// <summary>
    /// 启用文章
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <returns>操作结果</returns>
    [HttpPatch("{articleId}/enable")]
    public async Task<IActionResult> EnableArticle(Guid articleId)
    {
        var result = await _articleService.EnableArticleAsync(articleId);

        // 如果返回的是 ApiResult 类型
        if (result is ApiResult apiResult)
        {
            return apiResult.Code switch
            {
                1000 => Ok(apiResult),
                404 => NotFound(apiResult.Message),
                400 => BadRequest(apiResult.Message),
                _ => BadRequest(apiResult.Message)
            };
        }

        return Ok(result);
    }

    /// <summary>
    /// 禁用文章
    /// </summary>
    /// <param name="articleId">文章ID</param>
    /// <returns>操作结果</returns>
    [HttpPatch("{articleId}/disable")]
    public async Task<IActionResult> DisableArticle(Guid articleId)
    {
        var result = await _articleService.DisableArticleAsync(articleId);

        // 如果返回的是 ApiResult 类型
        if (result is ApiResult apiResult)
        {
            return apiResult.Code switch
            {
                1000 => Ok(apiResult),
                404 => NotFound(apiResult.Message),
                400 => BadRequest(apiResult.Message),
                _ => BadRequest(apiResult.Message)
            };
        }

        return Ok(result);
    }
}
